package net.huashitong.zhApp.controller;

import com.sirdc.modules.core.web.model.Message;
import com.sirdc.modules.utils.ObjectUtils;
import jodd.util.StringUtil;
import net.huashitong.Project.entity.MessageList;
import net.huashitong.Project.service.MessageListService;
import net.huashitong.node.entity.NodeNewschedules;
import net.huashitong.node.service.NodeNewschedulesService;
import net.huashitong.oversee.databean.SupervisionTaskDataBean;
import net.huashitong.oversee.entity.SupervisionLog;
import net.huashitong.oversee.entity.SupervisionTask;
import net.huashitong.oversee.entity.TaskRecord;
import net.huashitong.oversee.filter.SupervisionTaskFilter;
import net.huashitong.oversee.filter.TaskLogFilter;
import net.huashitong.oversee.filter.TaskRecordFilter;
import net.huashitong.oversee.service.SupervisionLogService;
import net.huashitong.oversee.service.SupervisionTaskService;
import net.huashitong.oversee.service.TaskRecordService;
import net.huashitong.user.entity.BnpUser;
import net.huashitong.zhApp.service.SupervisionTaskDetailService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.*;

@Controller
@RequestMapping(value = "/zhApp/supervisionTask")
public class AppSupervisionTaskController extends BaseCtrl {

    @Autowired
    private SupervisionTaskService taskService;
    @Autowired
    private SupervisionLogService supervisionLogService;
    @Autowired
    private MessageListService messageListService;
    @Autowired
    private NodeNewschedulesService nns;
    @Autowired
    private TaskRecordService taskRecordService;

    /**
     * 查询督查任务
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/lists", method = RequestMethod.POST)
    public Map<String, Object> supervisionTaskList(@RequestBody SupervisionTaskFilter filter) {
        BnpUser user = queryUserAuth(filter.getUserPhone());
        if (ObjectUtils.isBlank(user)) {
            Map<String, Object> result = new HashMap<>();
            result.put("code", "202");
            result.put("message", "无用户权限");
            return result;
        } else {
            filter.setUserinfo(user.getPhone());
            filter.setBranchType(user.getBranchType());
            filter.setRole(user.getRole());
            if(StringUtil.isNotBlank(filter.getSysId())){

            }
            List<SupervisionTask> resList = taskService.getTaskLists(filter);
            List<SupervisionTaskDataBean> sdbList = new ArrayList<>();
            if(ObjectUtils.isBlank(resList)){
                Map<String, Object> result = new HashMap<>();
                result.put("code", "200");
                result.put("message", "成功获取数据");
                result.put("userAuth", user);
                result.put("data", new ArrayList<>());
                result.put("count", 0);
                return result;
            }
            for (SupervisionTask task : resList) {
                SupervisionTaskDataBean sdb = new SupervisionTaskDataBean();
                //督查单位的<催办记录>
                List<SupervisionLog> logs = supervisionLogService.getMissionLog(task.getSysId());
                int supNum = logs.size();
                //被督查单位的<反馈记录>
                List<TaskRecord> records = taskRecordService.getRecordsById(task.getSysId());
                int resNum = records.size();
                BeanUtils.copyProperties(task, sdb);
                sdb.setSupervisionNum(supNum + "次");
                sdb.setResDeptNum(resNum + "次");
                if (supNum > 0) {
                    sdb.setSupervisionLastTime(logs.get(0).getCreateDate());
                } else {
                    sdb.setSupervisionLastTime("无");
                }
                if (resNum > 0) {
                    sdb.setResDeptLastTime(records.get(0).getCreateDate());
                } else {
                    sdb.setResDeptLastTime("无");
                }
                BeanUtils.copyProperties(task, sdb);
                sdbList.add(sdb);
            }
            Map<String, Object> result = new HashMap<>();
            result.put("code", "200");
            result.put("message", "成功获取数据");
            result.put("userAuth", user);
            result.put("data", sdbList);
            result.put("count", filter.getPaging().getRecords());
            return result;
        }
    }

    /**
     * 添加催办记录
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/createTaskLog", method = RequestMethod.POST)
    public Message createTaskLog(@RequestBody TaskLogFilter filter) {
        SupervisionTask task = taskService.getById(filter.getTaskId());
        if(ObjectUtils.isBlank(task)){
            //无添加记录
            Message message = new Message();
            message.setCode("201");
            message.setMessage("找不到相应的督查任务");
            message.setData(false);
            return message;
        }
        filter.setTasktimes(task.getTasktimes());
        boolean isRight = supervisionLogService.saveCuiBanLog(filter);
        if (!isRight) {
            //无添加记录
            Message message = new Message();
            message.setCode("201");
            message.setMessage("记录填写不规范");
            message.setData(false);
            return message;
        }
        //添加督查动态消息列表
        MessageList messageList = new MessageList();
        messageList.setIsRead("0");
        messageList.setTaskId(task.getSysId());
        messageList.setUserId(task.getUserid());
        messageListService.save(messageList);

        Message message = new Message();
        message.setCode("200");
        message.setMessage("提交成功");
        message.setData(true);
        return message;
    }

    /**
     * 完成情况提交（责任单位）
     **/
    @ResponseBody
    @RequestMapping(value = "/createRespRecord", method = RequestMethod.POST)
    public Message createCompleteInfo(@RequestBody TaskRecordFilter filter) {

        filter.setTaskId(filter.getSysId());
        filter.setSysId(null);
        SupervisionTask task = taskService.getById(filter.getTaskId());
        filter.setTaskName(task.getTaskName());
        filter.setResDept(task.getResDept());
        filter.setSupervisionTeamId(task.getGroupId());
        boolean flag = taskRecordService.saveRocord(filter); //保存完成情况
        if (!flag) {
            //无添加记录
            Message message = new Message();
            message.setCode("201");
            message.setMessage("记录填写不规范");
            message.setData(false);
            return message;
        }
        taskService.update(task);
        //添加督查动态消息列表
        MessageList messageList = new MessageList();
        messageList.setIsRead("0");
        messageList.setTaskId(task.getSysId());
        messageList.setUserId(task.getGroupId());
        messageListService.save(messageList);

        Message message = new Message();
        message.setCode("200");
        message.setMessage("添加成功");
        message.setData(true);
        return message;
    }


    /**
     * 查看节点情况
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryNodeDetail", method = RequestMethod.POST)
    public Message queryNodeDetail(@RequestBody SupervisionTaskFilter filter) {
        SupervisionTask task = taskService.getById(filter.getSysId());
        String nodeSysId = task.getNodeSysId();
        NodeNewschedules node = nns.getById(nodeSysId);
        if (ObjectUtils.isNotBlank(node)) {
            //已完成
            if ("2".equals(node.getStatus())) {
                Message message = new Message();
                message.setCode("200");
                message.setMessage("节点已完成");
                message.setData(true);
                return message;
            } else {
                Message message = new Message();
                message.setCode("200");
                message.setMessage("节点未完成");
                message.setData(false);
                return message;
            }
        } else {
            Message message = new Message();
            message.setCode("200");
            message.setMessage("节点未完成");
            message.setData(false);
            return message;
        }
    }

    /**
     * 督查过程日志
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryTaskLogs", method = RequestMethod.POST)
    public Map<String, Object> queryTaskLogs(@RequestBody SupervisionTaskFilter filter) {
        BnpUser user = queryUserAuth(filter.getUserPhone());
        if (ObjectUtils.isBlank(user)) {
            Map<String, Object> result = new HashMap<>();
            result.put("code", "202");
            result.put("message", "无用户权限");
            return result;
        }else{
            //督查记录（SupervisionLog）、完成情况（TaskRecord）
            SupervisionTask task = taskService.getById(filter.getSysId());
            //督查单位的<催办记录>
            List<SupervisionLog> logs = supervisionLogService.getMissionLog(filter.getSysId());
            //责任单位的<反馈记录>
            List<TaskRecord> records = taskRecordService.getRecordsById(filter.getSysId());

            List<SupervisionLog> newLogs = new ArrayList<>();
            for (TaskRecord log : records) {
                SupervisionLog supervisionLog = new SupervisionLog();
                supervisionLog.setTaxproof(log.getTaxproof());
                supervisionLog.setCreateDate(log.getCreateDate());
                supervisionLog.setCreateTime(log.getCreateTime());
                supervisionLog.setRecord(log.getRecord());
                supervisionLog.setTaskId(log.getTaskId());
                supervisionLog.setDatatime(log.getDatatime());
                supervisionLog.setSupervisionTeamId(log.getSupervisionTeamId());
                newLogs.add(supervisionLog);
            }
            logs.addAll(newLogs);
            Collections.sort(logs, new Comparator<SupervisionLog>() {
                @Override
                public int compare(SupervisionLog h1, SupervisionLog h2) {
                    String c1 = h1.getCreateDate() + " " + h1.getCreateTime();
                    String c2 = h2.getCreateDate() + " " + h2.getCreateTime();
                    return c1.compareTo(c2);
                }
            });
            Map<String, Object> result = new HashMap<>();
            result.put("code", "200");
            result.put("message", "成功获取数据");
            result.put("userAuth", user);
            result.put("task", task);
            result.put("data", logs);
            return result;
        }
    }

    @ResponseBody
    @RequestMapping(value = "/queryTaskDetailById", method = RequestMethod.POST)
    public Message queryTaskById(@RequestBody SupervisionTaskFilter filter) {
        SupervisionTask task = taskService.getById(filter.getSysId());
        Message message = new Message();
        message.setCode("200");
        message.setMessage("成功获取日志");
        message.setData(task);
        return message;
    }

}
